package com.qf.commons.sentinel.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.qf.commons.core.utils.JsonUtils;
import com.qf.data.r.Codes;
import com.qf.data.r.R;
import com.qf.data.r.RUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * description: 自定义的Sentinel的异常处理器
 * FlowException - 流量控制异常
 * DegradeException - 熔断降级异常
 * author: Ken
 * 公众号：Java架构栈
 */
public class SentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        //统一返回的对象
        R result = null;
        //判断异常
        if (e instanceof FlowException) {
            //流控异常
            result = RUtils.create(Codes.FLOW_ERROR);
        } else if(e instanceof DegradeException){
            //降级异常
            result = RUtils.create(Codes.DEGRADE_ERROR);
        } else {
            //默认异常
            result = RUtils.create(Codes.FAIL);
        }

        //将R对象转换成JSON串
        String json = JsonUtils.obj2Json(result);

        //设置响应体的响应码
        response.setStatus(result.getCode());
        //设置响应体类型
        response.setContentType("application/json;charset=utf-8;");
        response.setCharacterEncoding("UTF-8");
        //将R对象响应给客户端
        PrintWriter out = response.getWriter();
        out.print(json);
        out.close();
    }
}
